/* 
Copyright (c) 2004,2005, 2006, 2007, 2008 University of Illinois 

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/* Functions for the Log of DHTML/Widgets 
 * romanows, 3/10/06
 */
AccessibilityExtension.ns(function() { with (AccessibilityExtension.LIB) {

	var AE = AccessibilityExtension.ns;  
	AE.dialogName = "accessext-form-list-dhtmlrelationships";	

	var widgetarray = null;
	var tbObj;
	
	function relationObjectDisplayDetails() {}
	relationObjectDisplayDetails.prototype = {
		dataElementNames : ['icita07', 'icita08','source','relationship','destination','bidirectional'],
		columnHeaders : ['column.header.icita07.label', 'column.header.icita08.label','column.header.source.label','column.header.relationship.label','column.header.destination.label','column.header.bidirectional.label'],
		
		accessIssuesDataElementNames : ['emptydestination', 'undefinedrelation'],
		accessIssuesMessages : ['ariarelationships.warnings.emptydestination', 'ariarelationships.warnings.undefinedrelation'],
	
		accessIssuesUseObjectFunctions : true,
	}
	var relationObjectDisplayDetails = new relationObjectDisplayDetails();
	
	function relationObject(order,relationship,nodeSource,widgetIDSource,nodeDestination,widgetIDDestination,bidirectional,error,errorMsg) {
		this.order = order;
		this.relationship = relationship;
		this.node = nodeSource;
		this.nodeSource = nodeSource;
		this.source = widgetIDSource;
		this.nodeDestination = nodeDestination;
		this.destination = widgetIDDestination;
		this.bidirectional = bidirectional;
		this.error = error;
		this.errorMsg = errorMsg;
	}
	relationObject.prototype = {
		valid : false, 		// FIXME: what is this?
		icita07 : "",
		icita08 : "",
		order : null,
		relationship : null,
		node : null,  //same as nodeSource - for consistancy with tree list objects
		nodeSource : null,
		source : null,
		nodeDestination : null,
		destination : null,
		bidirectional : null,
		error : null,
		errorMsg : null,
		emptydestination : false,	
		undefinedrelation : false,	
		display : true,
		displayDetails: relationObjectDisplayDetails,
		getNoteText : function() {
			var note = '';
			var currStd = currStandard();
			if (this.errorMsg != null && currStd == 'icita08') {
				note = this.errorMsg + ' \n';
			}
			return note;
		},
		setRowColor : function (item) {
			var row = item.getElementsByTagName('treerow');
			if (this.errorMsg != null && this.errorMsg != "") {
				if (this.errorMsg.indexOf('Fail') > -1) {
					if (this.icita07) {
						row[0].setAttribute('properties','failRow');
					} else {
						row[0].setAttribute('properties','todoRow');
					}
				} else {
					if (this.icita07) {
						row[0].setAttribute('properties','warnRow');
					} else {
						row[0].setAttribute('properties','todoRow');
					}
				}
			}	
		},
		getTreeNode : function(windoc) {
			//var item = accesxt_generateTreeboxResults(windoc,this,['source','relationship','destination','bidirectional','error']);
			return accesxt_generateTreeboxResults(windoc,this,['source','relationship','destination','bidirectional']);
	//		this.(item);
	//		return item;
		},
	}
AccessibilityExtension.LIB.extend(AccessibilityExtension.LIB,
{
	/**
	 * Function for loading the widget relationships list headers.
	 * @return array of column headers for the widget list
	 * @author Sandy Foltz
	*/
	loadWidgetRelationshipsColumnHeaders: function() {
		var cols = new Array();
		cols['list-header-relationship'] = 'relationship';
		cols['list-header-source'] = 'source';	
		cols['list-header-destination'] = 'destination';
		cols['list-header-bidirectional'] = 'bidirectional';
	//	cols['list-header-error'] = 'error';
	   return cols;	
	},
	
	initTreeboxDHTMLRelationships: function() {
		var widgetRelationshipsColumnHeaders = loadWidgetRelationshipsColumnHeaders();
		tbObj = newTreeboxObject('treebox',widgetRelationshipsColumnHeaders,'list-header-relationship');
	},
	
	updatePointers: function() {
		try {  // from the accessibility Issues Dialog
			if (window.opener.name == 'accessext-issues') {
				var accessibilityIssuesDialog = window.opener.parent;
				AE.thewindow = accessibilityIssuesDialog.opener.parent._content;			
			} else {
				AE.thewindow = window.opener.parent._content;
			}
		} catch (e){
			try { // dialog way 
				AE.thewindow = window.opener.parent._content;
			} catch(e) {
				AE.thewindow = window.parent._content;
			}
		}
		AE.mydoc = AE.thewindow.document;
		AE.treebox = document.getElementById("treebox");
		widgetarray = new Array();
	
		initTreeboxDHTMLRelationships();
	},
	
	InitAccessibilityExt: function() {
		var dialogEle = document.getElementById("disable-highlighting-hbox");
		if (dialogEle == null) return; //not in listofdhtmlrelationships.xul so skip this function
		InitAccessibilityExt_common();
	},
	
	// Copied from RefreshList, should refresh the view without reloading widgetarray from the DOM tree
	RefreshListView: function() {
		var tempCurrentIndex=AE.treebox.currentIndex;
	
		tbObj.setDataArray(dataarray);
		UpdateTreeView();
		AE.treebox.view.selection.select(tempCurrentIndex);
	},
	
	// Scans the DOM to create a list of relevant objects and updates our tree view
	RefreshList: function() {
		AE.dataarray = new Array();
	
		updatePointers();
		
		var documents = accessext_getDocuments(AE.thewindow,new Array());
		
		for (var i=0; i < documents.length; i++) {
			ParseDocument(documents[i]);
		}
	
		tbObj.setDataArray(AE.dataarray);
		UpdateTreeView();
	},
	
	UpdateTreeView: function() {
		var widgetRelationshipsColumnHeaders = loadWidgetRelationshipsColumnHeaders();
		UpdateTreeView_common(AE.treebox,'relationship',AE.sortColumn,widgetRelationshipsColumnHeaders,AE.dataarray);
	},
	
	accessext_dhtmlRelationshipsClose: function() {
		CleanUp();
		window.close();
	},
	
	// When a row in the treebox_main is selected, this is called
	accessext_handle_treebox: function() {
		// If we've selected something sensical
		if(AE.treebox.currentIndex < 0 || AE.treebox.currentIndex >= AE.dataarray.length)
			return;
	
		accessext_setNoteText(AE.treebox.currentIndex);
		
		accessext_scrollAndHighlightNode(AE.dataarray[AE.treebox.currentIndex].nodeSource);
	},
	
	ParseDocument: function(doc) {
		AE.sortColumn = "list-header-relationship";
		ParseDocumentForWidgetRelationships(doc, AE.dataarray);
	},
	
	ParseDocumentForWidgetRelationships: function(node, loadArray) {
		var xpathResult = parseWidgetsFromDOM(node);	
		var r = xpathResult.iterateNext();
		widgetarray = new Array();
	
		while (r) {
			widgetarray[widgetarray.length] = newWidgetObject(widgetarray.length + 1, r);
			r = xpathResult.iterateNext();
		}
		
		// relationship-list parsing/generating code
		var relationshipAttributes = [
			'controls',
			'controlledby',
			'describedby',
			'labelledby',
			'hasparent',
			'haschild'
		];
		var relationshipBidirectional = [
			true,
			true,
			false,
			false,
			true,
			true
		];
		var relationshipConjugates = [
			'controlledby',
			'controls',
			'',
			'',
			'haschild',
			'hasparent'
		];
	
		var nada = /^\s*$/;  // regexp whitespace or nothing
		var errorMsg, error, nodeDestination, widgetIdDestination, bidirectional, destPtr, dest, destIdx;
		var emptydestination, undefinedrelation;
		var currStd = currStandard();
		for(var i=0; i<widgetarray.length; i++) {
			for(var j=0; j<relationshipAttributes.length; j++) {
				// Default values for display fields
				errorMsg = "";
				error = accessext_getBundleSingleString('ariarelationships.no');
				nodeDestination = [];
				widgetIdDestination = ""; //SMF 8/16/07 "none";
				bidirectional = '';
				emptydestination = false;
				undefinedrelation = false;
				
				// If this widget has one of the relationship attributes
				if(widgetarray[i].getState(relationshipAttributes[j]) != null ) {
					// Get the destination widget
					destPtr = widgetarray[i].getState(relationshipAttributes[j]).value;
					//if( nada.test(destPtr) ) {
					if( cleanSpaces(destPtr) == '') {
						emptydestination = true;
						var tmp = getErrMsgSeverity('ariarelationships.warnings.emptydestination', currStd) + ': ' +accessext_getBundleSingleString('ariarelationships.warnings.emptydestination');
						tmp = tmp.replace('%1', relationshipAttributes[j]);
						tmp += ' \n';
						errorMsg += tmp; //"ERROR: " + relationshipAttributes[j] + " is empty.";
						error = accessext_getBundleSingleString('ariarelationships.yes');
						nodeDestination = [];
						widgetIdDestination = "";
					}
	
					// This may be a list (?) (IDREFS, a space separated string), so search over the string
					dest = destPtr.split(/\s+/);
					for(var k=0; k<dest.length; k++) {					
						destIdx = findWidgetById(widgetarray, dest[k] );
						if( destIdx == null ) {
							if(relationshipAttributes[j] =='describedby' || relationshipAttributes[j] == 'labelledby') {
								var xpathResult = node.evaluate("//*[@id='" + dest[k] + "']", node, accessext_NSResolver, XPathResult.ANY_TYPE,null);
								destIdx = xpathResult.iterateNext();
								if (destIdx) widgetIdDestination = destIdx.tagName + ' tag'; 
							} if( destIdx == null) {
								undefinedrelation = true;
								var tmp = getErrMsgSeverity('ariarelationships.warnings.undefinedrelation', currStd) + ': ' + accessext_getBundleSingleString('ariarelationships.warnings.undefinedrelation');
								tmp = tmp.replace('%1', dest[k]);
								tmp = tmp.replace('%2', relationshipAttributes[j]);
								tmp += ' \n'; 
								errorMsg += tmp; //"Warn: The widget " + dest[k] + " referred to by " + relationshipAttributes[j] + " was not found on this page.";
								error = accessext_getBundleSingleString('ariarelationships.yes');
								if(widgetIdDestination != "") {
									widgetIdDestination += ", ";
								}
								widgetIdDestination = accessext_getBundleSingleString('ariarelationships.none'); //SMF 8/16/07
								bidirectional = accessext_getBundleSingleString('ariarelationships.error');
							}
						} else {
							widgetIdDestination = dest[k]; //SMF 8/16/07 + " not found";
							nodeDestination[nodeDestination.length + 1] = widgetarray[destIdx].node;
						
							// Bidirecionality can be 'yes', 
							// ... not applicable, not specified (no corresponding attribute or empty), 
							// ... error (something like a widgetID but not in our list),
							// ... or 'error' when a list has some of any of these conditions
							// In that case, the specifics will be displayed in the warning dialog
							if( relationshipBidirectional[j] ) {
								bidirectional = accessext_getBundleSingleString('ariarelationships.no');
								if( widgetarray[destIdx].getState(relationshipConjugates[j]) != null ) {
									// Account for IDREFS lists
									reverseDestIDREFS = widgetarray[destIdx].getState(relationshipConjugates[j]).value;
									reverseDest = reverseDestIDREFS.split(/\s+/);
									for(var m=0; m<reverseDest.length; m++) {		// FIXME: Could do this much better with RegExps
										if( reverseDest[m] == widgetarray[i].id ) {
											bidirectional = accessext_getBundleSingleString('ariarelationships.yes');
										}
									}
								}
							} else {
								bidirectional = accessext_getBundleSingleString('ariarelationships.no');
							}
							if(bidirectional == accessext_getBundleSingleString('ariarelationships.no')) {
								error = accessext_getBundleSingleString('ariarelationships.yes');
							}
						}
	
						// Defines one relationship between current widget (under consideration) and one of its targets
						loadArray[loadArray.length] = new relationObject(
							loadArray.length+1,
							relationshipAttributes[j],
							widgetarray[i].node,
							(widgetarray[i].id != '') ? widgetarray[i].id : widgetarray[i].node.tagName + ' tag',
							nodeDestination,
							widgetIdDestination,
							bidirectional,
							error,
							errorMsg
						);
						loadArray[loadArray.length-1].emptydestination = emptydestination;
						loadArray[loadArray.length-1].undefinedrelation = undefinedrelation;	
						if (emptydestination){k=dest.length;}	//there are no relations to be checked 	
					}
				}
			}
		}
	
		setMaxSeverityForArray(loadArray);
	},
	
	ARIARelationshipsRefresh: function() {
			tempCurrentIndex=document.getElementById('treebox').currentIndex;
			RefreshList();
			document.getElementById('treebox').view.selection.select(tempCurrentIndex);
			document.getElementById('treebox').focus();
			post_InitAccessibilityExt();
	},
	
	post_InitAccessibilityExt: function() {
		accessext_setNoteText(0);
	},
});
AccessibilityExtension.LIB.InitAccessibilityExt();	
}});